<template>
  <div class="diary-detail-container">
    <div class="header">
      <el-button @click="goBack">← 返回</el-button>
      <div class="actions" v-if="diary && diary.userId === userStore.userInfo.id">
        <el-button type="primary" @click="editDiary">编辑</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </div>
    </div>

    <div v-loading="loading" class="diary-content">
      <div v-if="diary" class="diary-card">
        <div class="diary-header">
          <div class="title-row">
            <span class="mood-icon">{{ getMoodEmoji(diary.mood) }}</span>
            <h2 class="diary-title">{{ diary.title }}</h2>
            <el-tag v-if="diary.isPrivate" type="warning">🔒 私密</el-tag>
          </div>
          <div class="meta-info">
            <span class="author">
              {{ diary.userId === userStore.userInfo.id ? '我' : 'TA' }}
            </span>
            <span class="date">{{ formatDateTime(diary.createdAt) }}</span>
            <span v-if="diary.weather" class="weather">
              {{ getWeatherEmoji(diary.weather) }} {{ diary.weather }}
            </span>
          </div>
        </div>

        <div class="diary-body">
          <p class="content">{{ diary.content }}</p>
        </div>
      </div>

      <el-empty v-else description="日记不存在或已被删除" />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑日记"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="日记标题" prop="title">
          <el-input
            v-model="editForm.title"
            placeholder="给今天的日记起个标题吧"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="今天心情" prop="mood">
          <el-radio-group v-model="editForm.mood">
            <el-radio-button label="happy">😊 开心</el-radio-button>
            <el-radio-button label="sad">😢 难过</el-radio-button>
            <el-radio-button label="excited">😆 兴奋</el-radio-button>
            <el-radio-button label="calm">😌 平静</el-radio-button>
            <el-radio-button label="angry">😠 生气</el-radio-button>
            <el-radio-button label="love">😍 甜蜜</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="今天天气">
          <el-radio-group v-model="editForm.weather">
            <el-radio-button label="晴天">☀️ 晴天</el-radio-button>
            <el-radio-button label="多云">⛅ 多云</el-radio-button>
            <el-radio-button label="阴天">☁️ 阴天</el-radio-button>
            <el-radio-button label="雨天">🌧️ 雨天</el-radio-button>
            <el-radio-button label="雪天">❄️ 雪天</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="日记内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="10"
            placeholder="记录今天发生的事情..."
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="隐私设置">
          <el-switch
            v-model="editForm.isPrivate"
            active-text="私密（只有我能看）"
            inactive-text="共享（TA也能看）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDiaryDetail, updateDiary, deleteDiary } from '@/api'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref(false)
const diary = ref(null)
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const submitting = ref(false)

const editForm = reactive({
  title: '',
  mood: 'happy',
  weather: '晴天',
  content: '',
  isPrivate: false
})

const rules = {
  title: [
    { required: true, message: '请输入日记标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入日记内容', trigger: 'blur' }
  ]
}

// 加载日记详情
const loadDiaryDetail = async () => {
  loading.value = true
  try {
    const res = await getDiaryDetail(route.params.id)
    if (res.code === 200) {
      diary.value = res.data
    } else {
      ElMessage.error(res.msg || '加载日记详情失败')
    }
  } catch (error) {
    console.error('加载日记详情失败：', error)
    ElMessage.error('加载日记详情失败')
  } finally {
    loading.value = false
  }
}

// 编辑日记
const editDiary = () => {
  editForm.title = diary.value.title
  editForm.mood = diary.value.mood
  editForm.weather = diary.value.weather || '晴天'
  editForm.content = diary.value.content
  editForm.isPrivate = diary.value.isPrivate
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await updateDiary(diary.value.id, {
          title: editForm.title,
          content: editForm.content,
          mood: editForm.mood,
          weather: editForm.weather,
          isPrivate: editForm.isPrivate
        })
        
        if (res.code === 200) {
          ElMessage.success('日记更新成功！')
          editDialogVisible.value = false
          loadDiaryDetail()
        } else {
          ElMessage.error(res.msg || '更新日记失败')
        }
      } catch (error) {
        console.error('更新日记失败：', error)
        ElMessage.error('更新日记失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除日记
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这篇日记吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteDiary(diary.value.id)
    if (res.code === 200) {
      ElMessage.success('日记删除成功！')
      router.push('/diary')
    } else {
      ElMessage.error(res.msg || '删除日记失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日记失败：', error)
      ElMessage.error('删除日记失败')
    }
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 获取心情 emoji
const getMoodEmoji = (mood) => {
  const moodMap = {
    'happy': '😊',
    'sad': '😢',
    'excited': '😆',
    'calm': '😌',
    'angry': '😠',
    'love': '😍'
  }
  return moodMap[mood] || '😊'
}

// 获取天气 emoji
const getWeatherEmoji = (weather) => {
  const weatherMap = {
    '晴天': '☀️',
    '多云': '⛅',
    '阴天': '☁️',
    '雨天': '🌧️',
    '雪天': '❄️'
  }
  return weatherMap[weather] || '☀️'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

onMounted(() => {
  loadDiaryDetail()
})
</script>

<style scoped>
.diary-detail-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.diary-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(255, 105, 180, 0.1);
}

.diary-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #ffe5f1;
}

.title-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.mood-icon {
  font-size: 32px;
}

.diary-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  flex: 1;
}

.meta-info {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #999;
}

.author {
  color: #ff69b4;
  font-weight: bold;
}

.diary-body {
  line-height: 1.8;
}

.content {
  font-size: 16px;
  color: #666;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>

